//
//  GetMediaListOperation.m
//  Vmix
//
//  Created by jeffs on 3/28/10.
//  Copyright 2010 VMIX Media Inc.. All rights reserved.
//

#import "GetMediaListOperation.h"
#import "VmixVideo.h"

@implementation GetMediaListOperation
@synthesize mediaData, mediaArray, delegate, mediaApi;


- (void)main {
	
	NSURL *url = [NSURL URLWithString: self.mediaApi];
	
	CXMLDocument *apiParser = [[[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil] autorelease];
    self.mediaArray = [[NSMutableArray alloc] init];
	NSArray *resultNodes = NULL;
    resultNodes = [apiParser nodesForXPath:@"//media" error:nil];
	
    for (CXMLNode *resultNode in resultNodes) {
		
		VmixVideo *video = [[VmixVideo alloc] init];
		video.media_id = [resultNode getElementValue:@"id" error:nil];
		video.partner_id = [resultNode getElementValue:@"partner_id" error:nil];
		video.title = [resultNode getElementValue:@"title" error:nil];
		video.description = [resultNode getElementValue:@"description" error:nil];
		video.class_id = [resultNode getElementValue:@"class_id" error:nil];
		video.date_created = [resultNode getElementValue:@"date_created" error:nil];
		video.date_approved = [resultNode getElementValue:@"date_approved" error:nil];
		video.last_modified =[ resultNode getElementValue:@"last_modified" error:nil];
		video.source_name = [resultNode getElementValue:@"source_name" error:nil];
		video.author = [resultNode getElementValue:@"id" error:nil];
		video.url = [resultNode getElementValue:@"id" error:nil];
		video.total_views = [resultNode getElementValue:@"total_views" error:nil];
		NSArray *formatNodes= NULL;
		NSArray *thumbNodes = NULL;
		formatNodes = [resultNode nodesForXPath:@"formats/format" error:nil];
		thumbNodes = [resultNode nodesForXPath:@"thumbnails/thumbnail" error:nil];
		
		for (CXMLNode *formatNode in formatNodes) {
			
			if([[formatNode getElementValue:@"format_id" error:nil] isEqual:DEFAULT_FORMAT ]){
				video.token = [formatNode getElementValue:@"token" error:nil];
			}
		}
		if(video.token == nil){
			video.token = [resultNode getElementValue:@"token" error:nil];
		}
		for (CXMLNode *thumbNode in thumbNodes) {
			
			if([[thumbNode getElementValue:@"is_default" error:nil] isEqual:@"1" ]){
				video.thumbnail = [thumbNode getElementValue:@"url" error:nil];
			}
		}
		
        [self.mediaArray addObject:video];
		//[video release];
		//[formatNodes release];
		//[thumbNodes release];
    }	
	
	[self.delegate didFinishParsingMedia:self.mediaArray];
	
}


@end
